/**
 * 蛇
 */
class Snake {

    //蛇元素
    snake: HTMLElement;

    //蛇头
    ele_head: HTMLElement;

    //蛇身体,包括蛇头
    bodies: HTMLCollection;


    constructor() {
        this.snake = document.getElementById('snake')!;
        this.ele_head = document.querySelector('#snake>div')!;
        this.bodies = this.snake.getElementsByTagName('div');
    }

    //获取蛇的坐标(蛇头)
    get x() {
        return this.ele_head.offsetLeft;
    }


    get y() {
        return this.ele_head.offsetTop;
    }

    //设置蛇的坐标(蛇头)
    set x(value: number) {
        if (this.x === value) {
            return;
        }
        //判断是否撞墙
        if (value < 0 || value > 290) {
            throw new Error("蛇撞墙了!");
        }

        //不能掉头
        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft === value) {
            if (value > this.x) {
                value = this.x - 10;
            } else {
                value = this.x + 10;
            }
        }

        //移动身体
        this.moveBody();

        this.ele_head.style.left = value + "px";
        this.checkHeadBody();
    }

    set y(value: number) {
        if (this.y === value) {
            return;
        }
        //判断是否撞墙
        if (value < 0 || value > 290) {
            throw new Error('蛇撞墙了!');
        }

        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === value) {
            if (value > this.y) {
                value = this.y - 10;
            } else {
                value = this.y + 10;
            }
        }

        //移动身体
        this.moveBody();

        this.ele_head.style.top = value + "px";
        this.checkHeadBody();
    }


    //增加身体
    addBody() {
        this.snake.insertAdjacentHTML('beforeend', "<div></div>")
    }

    //身体的移动
    moveBody() {
        //将后面一节的身体设置前一节的身体的位置
        for (let i = this.bodies.length - 1; i > 0; i--) {
            let X = (this.bodies[i - 1] as HTMLElement).offsetLeft;
            let Y = (this.bodies[i - 1] as HTMLElement).offsetTop;

            (this.bodies[i] as HTMLElement).style.left = X + "px";
            (this.bodies[i] as HTMLElement).style.top = Y + "px";
        }
    }

    //检查是否和自己相撞
    checkHeadBody() {
        for (let i = 4; i < this.bodies.length; i++) {
            let bd = this.bodies[i] as HTMLElement;
            if (this.x === bd.offsetLeft && this.y === bd.offsetTop) {
                throw new Error('撞到自己了!');
            }
        }
    }



}


export default Snake;